package com.chat.controller;

import com.chat.dto.MessageDTO;
import com.chat.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @Autowired(required = false)
    private SimpMessagingTemplate messagingTemplate;

    @PostMapping("/send")
    public ResponseEntity<MessageDTO> sendMessage(@RequestBody MessageDTO messageDTO) {
        MessageDTO saved = messageService.saveMessage(messageDTO);
        
        // 如果使用STOMP，发送给接收者
        if (messagingTemplate != null) {
            messagingTemplate.convertAndSend("/topic/messages/" + messageDTO.getReceiverId(), saved);
            messagingTemplate.convertAndSend("/topic/messages/" + messageDTO.getSenderId(), saved);
        }
        
        return ResponseEntity.ok(saved);
    }

    @GetMapping("/chat/{userId}/{otherUserId}")
    public ResponseEntity<List<MessageDTO>> getChatMessages(
            @PathVariable String userId,
            @PathVariable String otherUserId) {
        List<MessageDTO> messages = messageService.getChatMessages(userId, otherUserId);
        return ResponseEntity.ok(messages);
    }

    @MessageMapping("/chat")
    @SendTo("/topic/messages")
    public MessageDTO handleMessage(MessageDTO messageDTO) {
        MessageDTO saved = messageService.saveMessage(messageDTO);
        return saved;
    }
}

